import React, { Component } from 'react';
import { Card } from 'antd';
import {Link} from 'react-router-dom';
import Mutil from '../../../util/mm.js';
import Product from '../../../server/product-server.js';

const _mm = new Mutil();
const _product = new Product();

class CategoryList extends Component{
	constructor(props){
		super(props);
		this.state = {
			list   : [],
			parentCategoryId : this.props.match.params.categoryId || 0
		}
	}
	componentDidMount(){
		this.loadCategoryList();
	}
	componentDidUpdate(prevProps, prevState){
		let oldPath = prevProps.location.pathname,
			newPath = this.props.location.pathname,
			newId   = this.props.match.params.categoryId || 0;
		if(oldPath !== newPath){
			this.setState({
				parentCategoryId: newId
			}, () => {
				this.loadCategoryList();
			})
		}
	}
	//加载品类列表
	loadCategoryList(){
		_product.getCategoryList(this.state.parentCategoryId).then((res)=>{
			this.setState({
				list: res
			})
		},errMag =>{
			this.setState({
				list: []
			})
			_mm.errorTips(errMag)
		});
	}
	//跟新品类的名字
	onUpdateName(categoryId, categoryName){

		let newName = window.prompt('请输入新的品类名称', categoryName);
		if(newName){
			_product.updateCategoryName({
				categoryId: categoryId,
				categoryName: newName
			}).then(res=>{
				_mm.successTips(res);
				this.loadCategoryList();
			}, errMsg =>{
				_mm.errorTips(errMsg);
			})
		}
	}
	render() {
		let listBody = this.state.list.map((category, index)=>{
						return(
							<tr key={index}>
								<td>{category.id}</td>
								<td>{category.name}</td>
								<td>
									<a className="opear"
										onClick={(e)=>this.onUpdateName(category.id, category.name)}
									>修改名称</a>
									{
										category.parentId === 0 ?
										<Link to={`/product/category/${category.id}`}>查看子品类</Link>
										: null
									}
								</td>
							</tr>
						);
					});
		let listError = (
			<tr>
				<td colSpan="5" className="text-center">
					{this.state.firstLoading ? '正在加载...' : '没有找到相应的结果'}
				</td>
			</tr>
		);
		let tableBody = this.state.list.length > 0 ? listBody : listError;
		return (
			<Card title="品类列表">
				<div className="page-header-right">
					<Link to="/product/add" className="btn btn-primary">
						<i className="fa fa-plus"></i>
						<span>添加商品</span>
					</Link>
				</div>
				<div className="row">
					<div className="col-md-12">
						<p>父品类ID： {this.state.parentCategoryId}</p>
					</div>
				</div>
				<div className="row">
					<div className="col-md-12">
						<table className="table table-striped">
							<thead>
								<tr>
									<th>品类ID</th>
									<th>品类名称</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody>
								{tableBody}	
							</tbody>
						</table>
					</div>
				</div>
			</Card>
		);
	}
}

export default CategoryList;